import org.zkoss.zk.ui.api.*;
import org.zkoss.zul.Menubar;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import administrationPane.MainFrameController;
import administrationPane.CommandMgr;

public class DefaultCommandMgrImpl 
extends Menubar
implements CommandMgr{
	private HashMap menuItemMap;
	private MainFrameController mainFrame;
	
	public DefaultCommandMgrImpl(){
		super();
	}
	
	public void initialize(){
		menuItemMap=new HashMap();
		recurAdd();
		mainFrame=this.getPage().getFellow("ADMIN_MAIN_WND").getFellow("ADMIN_MAIN_FRAME");
	}
	
	private void recurAdd(){
		Iterator itr=this.getChildren().iterator();
		while(itr.hasNext())
			recurAddInner((Component)itr.next());
	}
	
	private void recurAddInner(Component root){
		Iterator itr=root.getChildren().iterator();
		while(itr.hasNext()){
			Component next=(Component)itr.next();
			if(next instanceof Menuitem)
				processItem((Menuitem)next);
			else{
				if(next instanceof Menu)
					processMenu((Menu)next);
				recurAddInner(next);
			}
		}
	}
	
	private void processItem(Menuitem item){
		String bindAppName=(String)item.getAttribute("APP_NAME");
		String commandName=(String)item.getAttribute("APP_COMMAND");
		
		if(bindAppName == null || bindAppName.equals("") ||
		   commandName == null || commandName.equals(""))
			return;
		else
		{
			HashMap subMap=(HashMap)menuItemMap.get(bindAppName);
			if(subMap == null){
				subMap=new HashMap();
				menuItemMap.put(bindAppName, subMap);
				subMap.put(commandName,item);
			}else
				subMap.put(commandName, item);
		}
	}
	
	private void processMenu(Menu item){
		String bindAppName=(String)item.getAttribute("APP_NAME");
		String appMenuId=(String)item.getAttribute("APP_MENU_ID");
		
		if(bindAppName == null || bindAppName.equals("") ||
		   appMenuId == null || appMenuId.equals(""))
			return;
		else
		{
			HashMap subMap=(HashMap)menuItemMap.get(bindAppName);
			if(subMap == null){
				subMap=new HashMap();
				menuItemMap.put(bindAppName, subMap);
				subMap.put(appMenuId,item);
			}else
				subMap.put(appMenuId, item);
		}
	}
	
	public void processCommand(Menuitem item){
		String bindAppName=(String)item.getAttribute("APP_NAME");
		String commandName=(String)item.getAttribute("APP_COMMAND");
		
		if(bindAppName == null || bindAppName.equals("") ||
		   commandName == null || commandName.equals(""))
			return;
		else
			mainFrame.processCommand(bindAppName,commandName,item);
	}
	
	public HashMap getMap(){
		return menuItemMap;
	}
}
